# Yousef Ourabi
# 09.16.2008
# Perl Prototype
package OtterFilter;

use strict;
use warnings;

use Apache2::Filter ();
use Apache2::RequestRec ();
use APR::Table ();
use Apache2::Const -compile => qw(OK);
use constant BUFF_LEN => 1024;


use LWP::Simple;
use LWP::UserAgent;
use HTTP::Response;

use Cache::Memcached;
use Data::Dumper;

my $DEBUG = $ENV{'DEBUG'} || 1;

use vars qw(@jhost $huri);

sub handler {
  my ($f, $bb) = @_;
  
  if ($DEBUG) {
    print STDERR "Staring Otter output filter \n";
  }
  
  unless ($f->ctx) {
    if ($DEBUG) {
      print STDERR "About to unset Content-Length HTTP header \n";
    }

    $f->r->headers_out->unset('Content-Length');
    $f->ctx(1);
  }
  

  # TODO: Grok when this does and doesn't branch.
  # Does happen on normal request
  # Does NOT happen when only doing HEAD / for example.
  while ($f->read(my $buffer, BUFF_LEN)) {
    if ($DEBUG) {
      print STDERR "Looking at buffer $buffer \n";
    }
    
    $f->print($buffer);
  }

  if ($DEBUG) {
    print STDERR "All done, returning OK status \n";
  }

  return Apache2::Const::OK;
}
1;
